/**
 * GB28181服务程序
 */
const parseString = require('xml2js').parseString;
const sip         = require('sip');
const log4js      = require('./sip_log');
const logger      = log4js.getLogger('info');
const config      = require('./sip_config');

//命令都放在这里
const command     = require('./sip_command');   
// 保存注册上来的设备
let devices = []; 
// 用来暂存上一次的request变量，方便组合下一次头信息
let s_rq;
/**
 * SIP服务端
 */
const sip_server={
  /**
  * 启动 sip 服务端
  */ 
  start : function(){
    logger.info('启动sip服务端');
    
    sip.start({
      logger: { 
        send: function(message, address) { 
          //logger.info("==send==:" , message,address); 
        },
        recv: function(message, address) {
          logger.info("==recv==:" , message,address); 
          //TODO: 不知道为什么这些消息在下面回调怎么取不到，临时放在这里处理
          let rq=message;
          if(!rq.method){
            if(rq.status==100){
              logger.info('retry');
            }else if(rq.status==400){
              logger.error('bad request');
            }else if(rq.status==200){
              logger.info('rq 200',rq);
              if(rq.headers.cseq.method=='INVITE'){
                // 回复ack
                command.ack(rq);
              }
            }
          }else if(rq.method==='BYE'){
            logger.info('===========TODO: 停止播放=============');
            sip.send(sip.makeResponse(rq,200,'OK'));
          }
          //-----------end todo------------
        }
      }
    },
    function(rq) {
      s_rq=rq;

      try {
        if(rq.method ==='REGISTER') {
          // 收到注册消息
          command.register(rq);
        }
        else if(rq.method==='BYE'){
          // 停止播放
          command.ack(rq);
        }
        else if(rq.method==='MESSAGE'){
          // 收到其它消息
          parseString(rq.content,function(err,result){
            if(result.Notify){
              let CmdType = result.Notify.CmdType[0];
              if(CmdType==='Keepalive'){
                command.keepalive(rq);
              }else{
                logger.error('未解析的指令',CmdType); 
              }
            }else if(result.Response){
              let CmdType = result.Response.CmdType;
              if(CmdType=='Catalog'){
                // 获取到的设备列表
                command.catalogAck(rq,result.Response.DeviceList);
              }
            }
          });
        }
        else if(rq.method=='ACK'){
          logger.info('ack');
        }
        else if(rq.method=='BYE'){
          logger.info('bye');
        }
        else {
          logger.debug(rq.method);
          sip.send(sip.makeResponse(rq, 405, 'Method Not Allowed'));
        }
      } catch(e) {
        logger.error(e);
        sip.send(sip.makeResponse(rq, 500, "Server Internal Error"));
      }
    });
    command.sip = sip;
  },
  /**
   * 
   * @param {发邀请目标} target 
   */
  invite:function(target){
    if(s_rq){
      command.invite(s_rq,target);
      return true;
    }
    else{
      return false;
    }
  },
  /**
   * 轮循有没有过期的
   * 国标定义，平台收不到心跳超过3次则判定设备离线，设备收不到心跳反馈3次则重新注册
   */
  keepalive:function(){
    setInterval(function(){
      for(var key in config.registry){

        if(!config.registry[key].online){
          let diff = ((new Date()).getTime() - config.registry[key].last)/1000;
          if(diff > config.sip.server.keepalive*3){
            config.registry[key].online=false;
          }
        }
      }
    },config.sip.server.keepalive*1000);
  }
}

module.exports = sip_server;
